package ysq.xyg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import ysq.xyg.model.Complain;
import ysq.xyg.model.Receiving;
import ysq.xyg.model.info.*;
import ysq.xyg.service.ComplainService;
import ysq.xyg.service.ItemService;
import ysq.xyg.service.ReceivingService;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.BaseUtil;
import ysq.xyg.util.DateUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.Date;

/**
 * 收货管理
 *
 * @author congcong tao
 * @create 2018/8/9 下午9:40
 */
@Controller
@RequestMapping("/receiving")
public class ReceivingController extends BaseController {

    private static Logger log= LoggerFactory.getLogger(ReceivingController.class);
    @Resource
    private ReceivingService receivingService;
    @Resource
    private ItemService itemService;
    @Resource
    private ComplainService complainService;

    private Receiving receiving;

    @RequestMapping("/listPage")
    public ModelAndView list(String status){
        ModelAndView view = new ModelAndView("/receivingList");
        view.addObject("status", status);
        return view;
    }

    /**
     * 管理端查看收货记录
     */
    @RequestMapping("/adminListPage")
    public ModelAndView listAdmin(){
        ModelAndView view = new ModelAndView("/receivingAdminList");
        return view;
    }

    /**
     * 收货员查看
     */
    @RequestMapping("/personalListPage")
    public ModelAndView listPersonal(){
        ModelAndView view = new ModelAndView("/receivingPersonalList");
        return view;
    }

    /**
     * 1、所有获奖记录，获取当前人中奖人选择
     * 2、查询转让记录，type=2，otherUserName可以当做
     */
    @RequestMapping(value = "/jsonList",method = RequestMethod.POST)
    public @ResponseBody JSONObject jsonList(Receiving receiving, Page page) throws MalformedURLException, UnsupportedEncodingException {
        PageInfo<Receiving> pageInfo = receivingService.pageInfo(receiving, page.getLimit(), page.getPage());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", pageInfo.getTotal());
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for (Receiving item : pageInfo.getList()) {
                row = new JSONObject();
                row.put("id", item.getId());
                row.put("activityTitle", item.getActivity().getTitle());
                row.put("otherUserName", item.getOtherUserName());
                row.put("transferPrice", item.getTransferPrice());
                row.put("winningNum", item.getActivity().getWinningNum());
                row.put("itemTitle", item.getItem().getTitle());
                row.put("createTime", DateUtil.DateToStr(item.getCreateTime(), DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    /**
     * 收货员查看自己的收货记录
     * type=2，并查询当前收货人的获取
     */
    @RequestMapping(value = "/jsonCurrentList",method = RequestMethod.POST)
    public @ResponseBody JSONObject jsonCurrentList(HttpServletRequest request, Receiving receiving, Page page) throws MalformedURLException, UnsupportedEncodingException {
        BaseUserInfo baseUserInfo = acceptCurrentUser(request);
        receiving.setOtherUser(baseUserInfo.getUserid());
        PageInfo<Receiving> pageInfo = receivingService.pageInfo(receiving, page.getLimit(), page.getPage());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", pageInfo.getTotal());
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for (Receiving item : pageInfo.getList()) {
                row = new JSONObject();
                row.put("id", item.getId());
                row.put("activityTitle", item.getActivity().getTitle());
                row.put("otherUserName", item.getOtherUserName());
                row.put("transferPrice", item.getTransferPrice());
                row.put("status", item.getStatus());
                row.put("winningNum", item.getActivity().getWinningNum());
                row.put("itemTitle", item.getItem().getTitle());
                row.put("createTime", DateUtil.DateToStr(item.getCreateTime(), DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/selectEntity",method = RequestMethod.GET)
    public ModelAndView selectEntity(String id){
        ModelAndView view = new ModelAndView("/receivingUpdateOrSave");
        receiving = receivingService.selectEntityById(id);
        view.addObject("receiving", receiving);
        return view;
    }

    /**
     * 收货员查询
     */
    @RequestMapping(value = "/selectPersonalEntity",method = RequestMethod.GET)
    public ModelAndView selectPersonalEntity(String id){
        ModelAndView view = new ModelAndView("/receivingPersonalUpdateOrSave");
        receiving = receivingService.selectEntityById(id);
        view.addObject("receiving", receiving);
        return view;
    }

    @RequestMapping(value = "/updateOrAddEntity",method = RequestMethod.POST)
    public @ResponseBody JSONObject updateOrAddEntity(ReceivingInfo receivingInfo) {
        ReturnInfo returnInfo = new ReturnInfo();
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isEmpty(receivingInfo.getId())) {
            receiving = new Receiving();
            receiving.setId(BaseUtil.uId());
            receiving.setItemId(receivingInfo.getItemId());
            receiving.setCreateTime(new Date());
            int id = receivingService.insert(receiving);
            if(id <= 0){
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_INSERT);
            }
        } else {
            receiving = receivingService.selectByPrimaryKey(receivingInfo.getId());
            // 转让
            receiving.setType(receivingInfo.getType());
            receiving.setPhone(receivingInfo.getPhone());
            receiving.setRedeemCode(receivingInfo.getRedeemCode());
            receiving.setName(receivingInfo.getName());
            receiving.setAddress(receivingInfo.getAddress());
            receiving.setTransferPrice(receivingInfo.getTransferPrice());
            receiving.setOtherUser(receivingInfo.getOtherUser());
            receiving.setWeChat(receivingInfo.getWeChat());
            receiving.setAlipay(receivingInfo.getAlipay());
            int id = receivingService.updateByPrimaryKey(receiving);
            if (id <= 0) {
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
        jsonObject.put("returnInfo", returnInfo);
        return jsonObject;
    }

    /**
     * 确认收货
     */
    @RequestMapping(value = "/updateStatus",method = RequestMethod.POST)
    public @ResponseBody JSONObject updateStatus(ReceivingInfo receivingInfo) {
        ReturnInfo returnInfo = new ReturnInfo();
        JSONObject jsonObject = new JSONObject();
        receiving = receivingService.selectByPrimaryKey(receivingInfo.getId());
        // 转让
        receiving.setStatus(receivingInfo.getStatus());
        receiving.setAlipay(receivingInfo.getAlipay());
        receiving.setWeChat(receivingInfo.getWeChat());
        receiving.setReceivingDesc(receivingInfo.getReceivingDesc());
        int id = receivingService.updateByPrimaryKey(receiving);
        if (id <= 0) {
            returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_UPDATE);
        }
        jsonObject.put("returnInfo", returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/deleteEntity",method = RequestMethod.GET)
    public @ResponseBody JSONObject deleteEntity(String id){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(id)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            int ids = receivingService.deleteByPrimaryKey(id);
            if(ids <= 0){
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_DELETE);
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    /**
     * 申诉
     */
    @RequestMapping(value = "/updateComplain",method = RequestMethod.POST)
    public @ResponseBody JSONObject updateComplain(ComplainInfo complainInfo) {
        ReturnInfo returnInfo = new ReturnInfo();
        JSONObject jsonObject = new JSONObject();
        Complain complain = new Complain();
        complain.setId(BaseUtil.uId());
        complain.setMemberId(complainInfo.getMemberId());
        complain.setActivityId(complainInfo.getActivityId());
        // 申诉中
        complain.setStatus(BaseConstant.BASE_FLAG_ONE);
        complain.setDescription(complainInfo.getDescription());
        complain.setOtherUser(complainInfo.getOtherUser());
        complain.setCreateTime(new Date());
        int id = complainService.insert(complain);
        if (id <= 0) {
            returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_UPDATE);
        }
        jsonObject.put("returnInfo", returnInfo);
        return jsonObject;
    }
}
